var express = require('express');
var router = express.Router();
var fs = require('fs')
var path = require('path')
var MongoClient = require('mongodb').MongoClient;
var config = require('../config/db')    //加载数据库配置模块
var passport = require('passport') 
var bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const mongdb = require('mongodb');
const { type } = require('os');

//获取地址信息
router.get('/getAddress',passport.authenticate('jwt',{session:false}),async function(req,res,next){
    let client = await MongoClient.connect(config.url) //获取数据库连接对象
    let db = client.db()
    let addresses = await db.collection('addresses').find({ }).toArray()
    if(addresses.length >= 0){
        res.json({code:200, message:'ok', data: addresses });
    }else{
        res.json({code:200, message:'error'});
    }
  });


//添加地址
router.post('/addAddress',async function(req,res,next){
    let{ userName,telephone,types,citys,address}  = req.body//获取加入地址所需信息
    let client = await MongoClient.connect(config.url) //获取数据库连接对象
    let db = client.db()
    let newAddress = {
        "name":userName,
        "telephone":telephone,
        "type":types,
        "city":citys,
        "address":address
    }
    let results = await db.collection('addresses').insertOne(newAddress)
    console.log('results:',results)
    //判断是否添加成功
    if(results.acknowledged){
        res.json({code:200,message:'ok'});
    }else{
        res.json({code:200,message:'error'});
    }
})

 // 删除地址
 router.delete('/delAddress',passport.authenticate('jwt',{session:false}),async function(req,res,next){
    let {id}= req.query  
    console.log('asd',id)                //获取需要删除的地址信息id
    let client = await MongoClient.connect(config.url) // 获取数据库连接对象 
    let db = client.db()
   let results = await db.collection('addresses').deleteOne({_id:new mongdb.ObjectId(id)})// 执行删除地址的操作
   console.log('results:',results)
    //判断是否删除成功
    if(results.acknowledged){
        res.json({code:200,message:'ok'});
   }else{
       res.json({code:200,message:'error'});
    }
   
   })

module.exports = router;